<?php
/**
 * @package EXCEL
 * @copyright Авторские права (C) 2010 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * Price Excel! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */


defined( '_JEXEC' ) or die( 'Restricted access' );
//error_reporting(E_ALL ^ E_NOTICE);
?>
<style>
    .smallgrey {
        color : #999;
        font-size : 10px;
    }
</style>
<?php


$id                  = JArrayHelper::getValue($_REQUEST, 'id', '');
$cid                 = JArrayHelper::getValue($_REQUEST, 'cid', '');
$catid               = JArrayHelper::getValue($_REQUEST, 'catid','');
$act                 = JArrayHelper::getValue($_REQUEST, 'act', null);
$task                = JArrayHelper::getValue($_REQUEST, 'task', null);
$option              = JArrayHelper::getValue($_REQUEST, 'option', null);
$access              = JArrayHelper::getValue($_REQUEST, 'access', '');
$name                = JArrayHelper::getValue($_REQUEST, 'name', '');
$descript        	 = JArrayHelper::getValue($_REQUEST, 'descript', '');
$ordering            = JArrayHelper::getValue($_REQUEST, 'ordering', '');
$ordering            = JArrayHelper::getValue($_POST, 'ordering', '');
$title               = JArrayHelper::getValue($_REQUEST, 'title', '');
$owner               = JArrayHelper::getValue($_REQUEST, 'owner','');
$filename         	 = JArrayHelper::getValue($_REQUEST, 'filename','');
$gentitle            = JArrayHelper::getValue($_POST, 'gentitle','');

$price_f      = @$_FILES['price_f']['tmp_name'];
$price_f_name = @$_FILES['price_f_name']['name'];

if (!defined( 'DS' )) {
    define( 'DS', DIRECTORY_SEPARATOR );
}
require_once( $mainframe->getPath( 'admin_html' ) );
require_once(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_excel'.DS.'class.excel.php');

require(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_excel'.DS.'config.excel.php');

JHTML::_('behavior.tooltip');
switch ($act) {
    case "showcat":
        $task = "showcat";
        break;
    case "upload":
        $task = "upload";
        break;
}

switch ($task) {
//------------------------------------------------
    case "newcat":         # создать новую категорию
        editCat( 0, $option);
        break;
    case "editcat":        #редактировать категорию
        editCat( $cid[0], $option );
        break;
    case "savecat":
        saveCat( $option , $task);
        break;
    case "removecat":      #удаление категорий
        removeCat( $cid, $option );
        break;
    case "cancelcat":      #отмена категорий
        cancelCat( $option );
        break;
    case "showcat":        #отобразить категории
        viewCat( $option );
        break;
    case "publishcat":     #показать категорию
        publishCat( $cid, 1, $option );
        break;
    case "unpublishcat":   #скрыть категорию
        publishCat( $cid, 0, $option );
        break;
    case "orderupcat":
        orderCat( $cid[0], -1, $option );
        break;
    case "orderdowncat":
        orderCat( $cid[0], 1, $option );
        break;
    //------------------------------------------------
    case "showprices":		#показать прайс
        showPrice( $option );
        break;
    case "upload":		#показать прайс
        showUpload( $option );
        break;
    case "cancel":
        $mainframe->redirect("index2.php?option=$option" );
        break;
    default:
        showPrice( $option );
        break;
    //------------------------------------------------
    case "uploadhandler":
        require(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_excel'.DS.'config.excel.php');
        $num = sprintf("%u", crc32($price_f)).'-'.$catid;
        $pricetype = 'XLS';

        $priceinfo = $pricetype;

        $price_f_name = $num.'.'.strtolower($priceinfo);

        if ( strlen( $price_f ) > 0 and $price_f != "none" ) {
            echo 'загружаем';
            copy($price_f, JPATH_SITE.DS.$jx_path.DS.$price_f_name);
        }

        $database = &JFactory::getDBO();
        $user = &JFactory::getUser();
        $date = mktime();
        $database->setQuery( "select ordering from #__price_excel where catid=$catid order by ordering desc limit 1" );
        $ordering1 = $database->loadResult();
        $ordering = $ordering1+1;
        $database->setQuery( "insert into #__price_excel(id,catid,title,owner,date,ordering,published,filename) VALUES (NULL,'$catid','$title','$user->username','$date','$ordering','0','$price_f_name')" );
        if (!$database->query()) {
            echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
            exit();
        }
        $mainframe->redirect( "index2.php?option=com_excel&act=showprices");
        break;

    case "publish":     #показать прайс
        publishPrice( $id, 1, $option );
        break;
    case "unpublish":   #скрыть прайс
        publishPrice( $id, 0, $option );
        break;
    case "orderup":
        orderPrice( $id[0], 1, $option );
        break;
    case "orderdown":
        orderPrice( $id[0], -1, $option );
        break;
    case "saveorder":
        saveOrder( $id );
        break;
    case "removeprice":      #удаление прайса
        removePrice( $id, $option );
        break;
    case "edit":
        editPrice( $option, $id[0] );
        break;
//-----------------------------------------------------------		
}
//прайсы

function editPrice( $option, $uid ) {

    $database = &JFactory::getDBO();
    require(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_excel'.DS.'config.excel.php');
    $row = new mosjxlspp( $database );
    $row->load( $uid );
    $clist = ShowDropDownCategoryList( $row->catid ,"catid",' size="1"');
    $imgFiles = JFolder::files( JPATH_SITE.'components/com_excel/prices' );
    $images = array( JHTML ::_('select.option', '', _DG_SELECT_MED_PIC) );

    foreach ($imgFiles as $file) {
        if (eregi( "xls", $file )) {
            $images[] = JHTML ::_('select.option', $file );
        }
    }
    $imagelist = JHTML::_('select.genericlist', $images, 'imgfilename', "class=\"inputbox\" size=\"1\""
            . " onchange=\"javascript:if (document.forms[0].imgfilename.options[selectedIndex].value!='') {document.imagelib3.src='..$jx_path/' + document.forms[0].imgfilename.options[selectedIndex].value} else {document.imagelib3.src='../images/M_images/blank.png'}\"",
            'value', 'text', $row->filename );

    $thuFiles = JFolder::files( JPATH_SITE."$jx_path" );
    $thumbs = array( JHTML ::_('select.option', '', _DG_SELECT_THUMB_PIC) );
    foreach ($thuFiles as $tfile) {
        if (eregi( "jpeg|gif|jpg|png", $tfile )) {
            $thumbs[] = JHTML ::_('select.option', $tfile );
        }
    }
    $thumblist = JHTML::_('select.genericlist', $thumbs, 'imgthumbname', "class=\"inputbox\" size=\"1\""
            . " onchange=\"javascript:if (document.forms[0].imgthumbname.options[selectedIndex].value!='') {document.imagelib2.src='..$ad_paththumbs/' + document.forms[0].imgthumbname.options[selectedIndex].value} else {document.imagelib2.src='../images/M_images/blank.png'}\"",
            'value', 'text', $row->imgthumbname );
    $orgFiles = JFolder::files( JPATH_SITE."$ad_pathoriginals" );
    $originals = array( JHTML ::_('select.option', '', _DG_SELECT_ORG_PIC) );
    foreach ($orgFiles as $ofile) {
        if (eregi( "jpeg|gif|jpg|png", $ofile )) {
            $originals[] = JHTML ::_('select.option', $ofile );
        }
    }
    $originallist = JHTML::_('select.genericlist', $originals, 'imgoriginalname', "class=\"inputbox\" size=\"1\""
            . " onchange=\"javascript:if (document.forms[0].imgoriginalname.options[selectedIndex].value!='') {document.imagelib.src='..$ad_pathoriginals/' + document.forms[0].imgoriginalname.options[selectedIndex].value} else {document.imagelib.src='../images/M_images/blank.png'}\"",
            'value', 'text', $row->imgoriginalname );
    if (!$uid) $row->published = 0;
    HTML_excel::editPrice( $option, $row, $clist, $originallist, $imagelist, $thumblist, $ad_pathoriginals, $ad_pathimages, $ad_paththumbs, $ad_thumbwidth, $ad_thumbheight, $ad_imgstyle );
}
function removePrice( $cid, $option ) {
    global $ad_pathimages, $ad_paththumbs, $ad_pathoriginals, $mainframe;

    $database = &JFactory::getDBO();
    require(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_excel'.DS.'config.excel.php');
    if (!is_array( $cid ) || count( $cid ) < 1) {
        echo "<script> alert('" . JText::_('select an item to delete') . "'); window.history.go(-1);</script>\n";
        exit;
    }

    if (count( $cid )) {
        for ($i = 0; $i < count($cid); $i++) {

            $database->setQuery( "select id, filename from #__price_excel where id = $cid[$i]" );
            if ($database->query()) {
                $rows = $database->loadObjectList();
                $row = $rows[0];
                if (removeFile($row->filename, JPATH_SITE.DS.$jx_path)) {
                } else {
                    die(_DG_FFFFFFF);
                }
            } else {
                echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
            }
        }
        if (count( $cid )) {
            $cids = implode( ',', $cid );
            $database->setQuery( "DELETE from #__price_excel where id IN ($cids)" );
            if (!$database->query()) {
                echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
            }
        }
    }
    $mainframe->redirect( "index2.php?option=$option" );
}
function showPrice( $option ) {
    global  $mainframe, $group;
    $database = &JFactory::getDBO();
    $catid      = $mainframe->getUserStateFromRequest("catid{$option}", 'catid', 0);
    $search     = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
    $search     = $database->getEscaped(trim(strtolower($search)));
    $sort       = $mainframe->getUserStateFromRequest("sort{$option}",'sort', 0);
    $sorder     = $mainframe->getUserStateFromRequest("sorder{$option}",'sorder', 0);
    $limit      = $mainframe->getUserStateFromRequest('viewlistlimit', 'limit', 10);
    $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

    $where = array();
    if ($catid > 0) {
        $where[] = "catid='$catid'";
    }
    if ($sort == 1) {
        $where[] = "approved = 0";
    }
    if ($sort == 2) {
        $where[] = "approved = 1";
    }
    if ($sort == 3) {
        $where[] = "useruploaded = 1";
    }
    if ($sort == 4) {
        $where[] = "useruploaded = 0";
    }
    if ($sorder == 0) {
        $sortorder = "a.catid asc, a.ordering desc, date desc, title asc";
    }
    if ($sorder == 1) {
        $sortorder = "a.catid asc, a.ordering asc, date desc, title asc";
    }

    if ($search) {
        $where[] = "lower(imgtitle) like '%$search%' or lower(imgtext) like '%$search%'";
        $group = "group by id";
    }

    $database->setQuery( "select count(*) from #__price_excel as a " . (count($where) ? ' where ' . implode(' and ', $where) : ''));
    $total = $database->loadResult();
    echo $database->getErrorMsg();
    if ($limit > $total) {
        $limitstart = 0;
    }

    $where[] = 'a.catid = cc.cid';
    $picincat = count($where) ? ' where ' . implode(' and ', $where) : '';
    $database->setQuery( "select a.*, cc.name as category "
            . "from #__price_excel as a, #__price_excel_cat "
            . "as cc $picincat $group "
            . "order by $sortorder limit $limitstart, $limit" );
    $rows = $database->loadObjectList();
    if ($database->getErrorNum()) {
        echo $database->stderr();
        return false;
    }

    $clist = ShowDropDownCategoryList($catid, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"');

    $s_options[] = JHTML ::_('select.option', _DG_SHOW_ALL_PICT, 0);
    $s_options[] = JHTML ::_('select.option',"1",_DG_NOT_APPROVED);
    $s_options[] = JHTML ::_('select.option',"2",_DG_APPROVED);
    $s_options[] = JHTML ::_('select.option',"3",_DG_USER_UPLOAD_PIC);
    $s_options[] = JHTML ::_('select.option',"4",_DG_ADMIN_UPLOAD_PIC);
    $slist = JHTML ::_('select.genericlist', $s_options, 'sort', 'class="inputbox" size="1" onchange="document.adminForm.submit();"','value', 'text', $sort);

    jimport('joomla.html.pagination');
    $pageNav = new JPagination( $total, $limitstart, $limit );
    HTML_excel::showPrice($option, $rows, $clist, $slist, $search, $pageNav);
}
function publishPrice( $pid=null, $publish=1,  $option ) {   #показать/скрыть прайсы

    global $mainframe;
    $database = &JFactory::getDBO();
    if (!is_array( $pid ) || count( $pid ) < 1) {
        $action = $publish ? 'publish' : 'unpublish';
        echo "<script> alert('" . JText::_('select an item to publish') . " $action'); window.history.go(-1);</script>\n";
        exit;
    }
    $pids = implode( ',', $pid );
    $database->setQuery( "update #__price_excel set published='$publish' where id IN ($pids)" );
    if (!$database->query()) {
        echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
        exit();
    }
    $mainframe->redirect( "index2.php?option=$option" );
}
function saveOrder( &$cid ) {

    $database = &JFactory::getDBO();
    $total  = count( $cid );
    $order  = JRequest::getVar( 'order' );

    for( $i=0; $i < $total; $i++ ) {
        $query = "update #__price_excel set ordering = ".(int)$order[$i]." where id = ".(int)$cid[$i];
        $database->setQuery( $query );
        if (!$database->query()) {
            echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
            exit();
        }

        $row = new mosjxlspp($database);
        $row->load($cid[$i]);
        $row->updateOrder(' ');
    }
    $mainframe->redirect('index2.php?option=com_excel', JText::_('new ordering saved'));
}
function orderPrice( $uid, $inc, $option ) {
    global  $mainframe;

    $database = &JFactory::getDBO();
    $database->setQuery( "select catid from #__price_excel where id=$uid");
    $piccatid = $database->loadResult();

    $database->setQuery( "select ordering, id from #__price_excel where id=$uid");
    $result = $database->query();
    $id1 = mysql_result($result, 0, 'id');
    $ordering1 = mysql_result($result, 0, 'ordering');

    if ($inc==1) {
        $database->setQuery( "select ordering, id from #__price_excel where catid=$piccatid and ordering > $ordering1 order by ordering limit 1");
    } else {
        $database->setQuery( "select ordering, id from #__price_excel where catid=$piccatid and ordering < $ordering1 order by ordering desc limit 1");
    }
    $result = $database->query();

    $ordering2 = mysql_result($result, 0, 'ordering');
    $id2 = mysql_result($result, 0, 'id');

    $database->setQuery( "update #__price_excel set ordering=$ordering1 where id=$id2");
    $result = $database->query();
    $database->setQuery( "update #__price_excel set ordering=$ordering2 where id=$id1");
    $result = $database->query();

    $mainframe->redirect('index2.php?option=com_excel' );
}
function showUpload( $option ) {
    global $mainframe;

    $database = &JFactory::getDBO();
    $user = &JFactory::getUser();
    require_once(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_excel'.DS.'class.excel.php');
    $clist = ShowDropDownCategoryList(0,'catid',' class="inputbox" size="1" style="width:197;"');
    echo "<script type=\"text/javascript\">\n";
    echo "function BatchFormCheck(theForm) {\n";
    echo "var form = document.adminForm;\n";
    echo "if (form.title.value == \"\") {\n";
    echo "alert('".JText::_('pex must_have_title')."');\n";
    echo "return false;\n";
    echo "} else if (form.catid.value == \"0\") {\n";
    echo "alert('".JText::_('pex must_select_category')."');\n";
    echo "return false;\n";
    echo "} else if (form.price_f.value == \"\") {\n";
    echo "alert('".JText::_('pex must_have_fname')."');\n";
    echo "return false;\n";
    echo "} else {\n";
    echo "form.submit();\n";
    echo "jxLoading();\n";
    echo "}\n";
    echo "}\n";
    echo "</script>\n";
    echo "<script type=\"text/javascript\">\n";
    echo "var xmlhttp;\n";
    echo "try{xmlhttp = new XMLHttpRequest();}catch(e){\n";
    echo "try{xmlhttp = new ActiveXObject(\"Msxml2.XMLHTTP\");}catch(e){\n";
    echo "try{xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");}catch(e){}}}\n";
    echo "function jxLoading() {\n";
    echo "if(!xmlhttp)return alert(\"No Http Transport.\");\n";
    echo "xmlhttp.open(\"GET\",document.location.href,true);\n";
    echo "xmlhttp.onreadystatechange = function() {\n";
    echo "if (xmlhttp.readyState == 4) {\n";
    echo "document.getElementById(\"status\").innerHTML = '<img src=\"".$mainframe->getSiteURL()."administrator/components/com_excel/images/loading.gif\" alt=\"loading\" width=\"101\" height=\"13\" border=\"0\" align=\"absmiddle\">'\n";
    echo "}\n";
    echo "}\n";
    echo "xmlhttp.send(null);\n";
    echo "}\n";
    echo "</script>";
    echo "<table class=\"adminheading\">\n";
    echo "<tr>\n";
    echo "<th class='mediamanager'>".JText::_('pex upload_new_price')."</th>\n";
    echo "</tr>\n";
    echo "</table>";
    echo "<form action='index2.php?task=uploadhandler' method='post' name='adminForm' enctype='multipart/form-data' onSubmit=\"return BatchFormCheck(this)\">";
    echo "<table class=\"adminform\">\n";
    echo "<tr>\n";
    echo "<td width='10%' align='right'> ".JText::_('title').":</td>\n";
    echo "<td width='40%'>\n";
    echo "<input class='inputbox' type='text' name='title' size='34' maxlength='100' value='".htmlspecialchars($title, ENT_QUOTES)."' />";
    echo "</td>\n";
    echo "</tr>\n";
    echo "<tr>\n";
    echo "<td valign='top' align='right'>".JText::_('category').":</td>\n";
    echo "<td>\n";
    echo $clist;
    echo "</td>\n";
    echo "</tr>\n";
    echo "<tr>\n";
    echo "<td valign='top' align='right'>".JText::_('pex price').":</td>\n";
    echo "<td>\n";
    echo "<input class='inputbox' type='file' name='price_f'/> ".JHTML::_('tooltip', JText::_('pex max_filesize').": <strong>".ini_get('upload_max_filesize')."</strong>")."";
    echo "</td>\n";
    echo "</tr>\n";
    echo "<tr>\n";
    echo "<td></td>";
    echo "<td>\n";
    echo "<input type='hidden' name='option' value='$option' />";
    echo "<input type='hidden' name='owner' value='$user->username' />";
    echo "<div id='status'><input type='submit' value='".JText::_('pex upload')."' class='button' /></div>";
    echo "</td>\n";
    echo "</tr>\n";
    echo "</table>\n";
    echo "</form>";
}
//категории
function editCat( $uid, $option ) {                          #создание и редактирование категорий

    $database = &JFactory::getDBO();

    $row = new mosCats( $database );
    $row->load( $uid );
    $orders    = JHTML::_('list.genericordering', 'select ordering as value, name as text from #__price_excel_cat order by ordering desc' );
    $orderlist = JHTML ::_('select.genericlist', $orders, 'ordering', 'class="inputbox"', 'value', 'text', intval( $row->ordering ) );
    $yesno[]   = JHTML ::_('select.option', '0', JText::_('no') );
    $yesno[]   = JHTML ::_('select.option', '1', JText::_('yes') );
    $publist   = JHTML ::_('select.genericlist', $yesno, 'published', 'class="inputbox"', 'value', 'text', $row->published );
    $database->setQuery( "select id as value, name as text from #__groups order by id" );
    $groups    = $database->loadObjectList();
    $glist     = JHTML ::_('select.genericlist', $groups, 'access', 'class="inputbox"', 'value', 'text', intval( $row->access ) );
    HTML_excel::editCats( $row, $publist, $option , $glist , $Lists, $orderlist );
}

function saveCat( $option, $task ) {
    global $mainframe;

    $database = &JFactory::getDBO();

    $row = new mosCats( $database );
    if (!$row->bind( $_POST )) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
    }
    jimport('joomla.filter.output');
    JFilterOutput::objectHTMLSafe($row->name);
    if (!$row->check()) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$row->store()) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
    }
    $row->checkin();
    $row->reorder( "" );
    $mainframe->redirect( "index2.php?option=$option&task=showcat" );
}
function viewCat( $option) {                                 #отображение категорий
    global  $mainframe;
    $database = &JFactory::getDBO();
    $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
    $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
    $search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
    $search = $database->getEscaped( trim( strtolower( $search ) ) );
    $where = "";
    if ($search) {
        $where = " where a.name like '%$search%' or a.descript like '%$search%'";
    }

    $database->setQuery( " select count(*) from #__price_excel_cat AS a $where " );
    $total = $database->loadResult();
    require_once( "includes/pageNavigation.php" );
    $pageNav = new mosPageNav( $total, $limitstart, $limit  );
    $database->setQuery( " select a.*, g.name AS groupname "
            . " from #__price_excel_cat AS a "
            . " left join #__groups AS g on g.id = a.access "
            . " $where "
            . " order by a.ordering desc "
            . " limit $pageNav->limitstart, $pageNav->limit "
    );
    $rows = $database->loadObjectList();
    HTML_excel::showCats( $rows, $search, $pageNav, $option );
}
function removeCat( $cid, $option ) {                        #удаление категорий
    global $mainframe;
    $database = &JFactory::getDBO();
    if (count( $cid )) {
        $cids = implode( ',', $cid );
        foreach ($cid as $cc) {
            $database->setQuery( "delete from #__price_excel_cat where cid=$cc" );
            $database->query();
            echo $database->getErrorMsg();
        }
    }
    $mainframe->redirect( "index2.php?option=$option&task=showcat",$error);
}	
function cancelCat( $option ) {                              #отмена категории
    global $mainframe;
    $database = &JFactory::getDBO();
    $row = new mosCats( $database );
    $row->bind( $_POST );
    $row->checkin();
    $mainframe->redirect( "index2.php?option=$option&task=showcat" );
}
function publishCat( $cid=null, $publish=1, $option ) {      #показать/скрыть категории

    global $mainframe;
    $database = &JFactory::getDBO();
    if (!is_array( $cid ) || count( $cid ) < 1) {
        $action = $publish ? 'publish' : 'unpublish';
        echo "<script> alert('".JText::_('select an item to publish')." $action'); window.history.go(-1);</script>\n";
        exit;
    }
    $cids = implode( ',', $cid );
    $database->setQuery( "update #__price_excel_cat set published='$publish' where cid in ($cids)" );
    if (!$database->query()) {
        echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
        exit();
    }
    if (count( $cid ) == 1) {
        $row = new mosCats( $database );
        $row->checkin( $cid[0] );
    }
    $mainframe->redirect( "index2.php?option=$option&task=showcat" );
}

function GetNumberOfLinks ($cat) {                            #возвращает количество файлов
    $database = &JFactory::getDBO();
    $queue[] = intval($cat);
    while (list($key, $cat) = each($queue)) {
        $database->setQuery("select cid from #__price_excel_cat where published=1");
        $result = $database->query();
        $total = mysql_num_rows($result);
        $j = 0;
    }
    reset($queue);
    $query = "select count(*) from #__price_excel  where ( 0!=0";
    while (list($key, $cat) = each($queue)) {
        $query .= " or catid = $cat";
    }
    $query = $query . " ) and published=1";

    $database->setQuery($query);
    $result = $database->query();
    $val = mysql_fetch_row($result);
    return $val[0];
}
function ShowCategoryPath ($cat) {
    global  $gid, $dgurl;
    $database = &JFactory::getDBO();
    $cat = intval($cat);
    $parent = 1000;
    while ($parent) {
        $database->setQuery( "select * from #__price_excel_cat where cid=$cat" );
        $rows    = $database->loadObjectList();
        $row     = &$rows[0];
        $parent  = $row->parent;
        $name    = $row->name;
        if (empty($path)) {
            $path = $name;
        } else {
            $path = $name . ' &raquo; ' . $path;
        }
        $cat = $parent;
    }
    return $path . " ";
}
function ShowDropDownCategoryList($cat,$cname="cat",$extra=null,$flag=0) {
    $database = &JFactory::getDBO();
    $category        = "<select name='$cname' class='inputbox' $extra>";
    if($flag==1) {
        $add_category = true;
    }
    if(@$add_category) {
        $category       .= "<option value=0>".JText::_('select category')."</option>";
    } else {
        $category       .= "<option value='0'>".JText::_('select category')."</option>";
    }
    $database->setQuery( "select * from #__price_excel_cat order by cid asc" );
    $result= $database->query();
    $num_rows = mysql_num_rows($result);
    $i = 0;
    while($i < $num_rows) {
        $category_id = mysql_result($result,$i,"cid");
        $category_name = mysql_result($result,$i,"name");
        if($category_id != @$hide) {
            @$category_list .= "<option value='$category_id' ";
            if($category_id == $cat) {
                $category_list  .= " selected";
            }
            $category_list  .= ">".ShowCategoryPath($category_id)."</option>\n";
        }
        $i++;
    }
    $categories = explode("\n",$category_list);
    asort($categories);
    $category       .= implode("\n",$categories);
    $category       .= "</select>";
    return $category;
}
function orderCat( $uid, $inc, $option ) {

    global $mainframe;
    $database = &JFactory::getDBO();
    $fp = new mosCats( $database );
    $fp->load( $uid );
    $fp->move( $inc );
    $mainframe->redirect( "index2.php?option=$option&task=showcat" );
}
function format_filesize($tfilesize) {
    if ($tfilesize >= 1073741824) {
        $jxfilesize = number_format(($tfilesize / 1073741824), 1) .' '. JText::_('pex filesize_gb');
    } elseif ($tfilesize >= 1048576) {
        $jxfilesize = number_format(($tfilesize / 1048576), 1) .' '. JText::_('pex filesize_mb');
    } elseif ($tfilesize >= 1024) {
        $jxfilesize = number_format(($tfilesize / 1024), 1) .' '. JText::_('pex filesize_kb');
    } elseif ($tfilesize >= 0) {
        $jxfilesize = $tfilesize .' '. JText::_('pex filesize_bytes');
    } else {
        $jxfilesize = "0 ".JText::_('pex filesize_bytes');
    }
    return $jxfilesize;
}
function removeFile($srcFilename, $srcFilePath) {
    $removeFilename = $srcFilePath . '/' . $srcFilename;
    if (unlink($removeFilename)) {
        return true;
    } else {
        return false;
    }
}
echo "<br><div class='smallgrey' align='center'>".$jx_cr."</div>";
?>
